import Vue from 'vue';
import axios from 'axios';
import Qs from 'qs';

//配置开发环境 or 生产环境
let apiURL = window.location.origin;
if(process.env.NODE_ENV == 'development') {
	axios.defaults.withCredentials = true; //携带cookie
	apiURL = '/api';
}
if(process.env.NODE_ENV == 'production') {
	axios.defaults.withCredentials = false; //携带cookie
}

axios.defaults.timeout = 30000;
axios.defaults.baseURL = apiURL;

// http请求拦截器
axios.interceptors.request.use(config => {
	return config;
}, error => {
	return Promise.reject(error);
});

// http响应拦截器
axios.interceptors.response.use(data => {
	return data;
}, error => {
	return Promise.resolve({
		data: {
			result: {
				code: 401,
				error: 'The server error',
			}
		}
	});
});

export default async(method = 'get', url = '', data = {}) => {
	let methodType = method;
	let params = {};
	let headers = {
		'Content-Type': 'application/x-www-form-urlencoded',
	}
	if(method == 'get') {
		Object.keys(data).forEach(key => {
			params[key] = data[key];
		});
	}
	if(method == 'post') {
		data = Qs.stringify(data);
	}
	if(method == 'file') {
		methodType = 'post';
	}
	let requestConfig = {
		url: url,
		method: methodType,
		params: params,
		data: data,
		responseType: 'json',
		headers: headers
	}
	try {
		const response = await axios(url, requestConfig);
		return response.data;
	} catch(error) {
		throw new Error(error);
	}
};

/**
 * Content-Type常用参数:
 * application/json;charse=UTF-8
 * application/x-www-form-urlencoded
 * multipart/form-data
 */